package com.xie.authority_system.controller;

import com.xie.authority_system.entity.Permission;
import com.xie.authority_system.service.PermissionService;
import com.xie.authority_system.utils.Result;
import com.xie.authority_system.vo.query.PermissionQueryVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 谢金成
 * @date 2024/1/8 14:58
 */
@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:select')")
    public Result getPermissionList() {
        List<Permission> permissionList = permissionService.findPermissionList();
        return Result.ok(permissionList);
    }

    @GetMapping("/parent/list")
    @PreAuthorize("hasAuthority('sys:menu:select')")
    public Result getParentPermissionList() {
        List<Permission> parentPermissionList = permissionService.findParentPermissionList();
        return Result.ok(parentPermissionList);
    }

//    @GetMapping("/{id}")
//    public Result getMenuById(@PathVariable Long id) {
//        return Result.ok(permissionService.getById(id));
//    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:menu:add')")
    public Result addPermission(@RequestBody PermissionQueryVo permissionQueryVo) {
        if (permissionService.save(permissionQueryVo)) {
            return Result.ok().message("菜单增加成功!");
        }

        return Result.error().message("菜单增加失败!");
    }

    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:edit')")
    public Result editPermission(@RequestBody PermissionQueryVo permissionQueryVo) {
        if (permissionService.updateById(permissionQueryVo)) {
            return Result.ok().message("菜单修改成功!");
        }

        return Result.error().message("菜单修改失败!");
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result deletePermissionById(@PathVariable Long id) {
        if (permissionService.removeById(id)) {
            return Result.ok().message("菜单删除成功!");
        }

        return Result.error().message("菜单删除失败!");
    }

    @GetMapping("/check/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result hasChildrenOfPermission(@PathVariable Long id) {
        if (permissionService.hasChildrenOfPermission(id)) {
            return Result.exist().message("该菜单下有子菜单, 不能删除!");
        }

        return Result.ok();
    }
}
